# -*- coding: utf-8 -*-

"""
* Copyright (C) 2016 GridSafe, Inc.
"""
import jwt
import time
import redis
import hashlib
from time import time
from django.conf import settings
from django.http import JsonResponse
from django.contrib import messages
from django.http.response import HttpResponse
from rest_framework.response import Response
from apps.wallet import constants


def redis_client():
    client = redis.StrictRedis(host=settings.REDIS_HOST_MASTER, port=settings.REDIS_PORT)


def api_fail_response(code, message, rtype='django'):
    data = {
        "error_code": code,  # 错误码, 非0
        "reason": message,
        "results": []
    }
    if rtype == 'django':
        return JsonResponse(data)

    #: return django rest framework Response, not Django built-in Response
    return Response(data)


def api_success_response(result, extra_data=None, rtype='django',
                         list_like=True):
    if rtype == 'raw':
        return HttpResponse(result)
    elif rtype == 'raw_json':
        return HttpResponse(result, content_type='application/json')

    data = {
        "error_code": constants.OPERATION_SUCCESS,
        "reason": "正常",
        "results": result
    }

    if extra_data and isinstance(extra_data, dict):
        data.update(extra_data)

    if not list_like:
        data.pop("results")
        data.update(result)

    if rtype == 'django':
        return JsonResponse(data)

    #: return django rest framework Response, not Django built-in Response
    return Response(data)


def flash(request, title, text, level='info'):
    """
    利用django的message系统发送一个信息，对接模板的sweetalert。
    """
    level_map = {
        'info': messages.INFO,
        'debug': messages.DEBUG,
        'success': messages.SUCCESS,
        'warning': messages.WARNING,
        'error': messages.ERROR
    }

    level = level_map[level]

    messages.add_message(request, level, text, extra_tags=title)
    return 'ok'


def create_params_sign(params, app_key):
    """根据参数生成 sign"""
    sorted_tuple_list = sorted(params.items(), key=lambda n: n[0])
    sorted_string_list = ["{}={}".format(item[0], item[1]) for item in
                          sorted_tuple_list]
    params_signature = "&".join(sorted_string_list)

    # 拼接API密钥
    string_sign_temp = params_signature + "&key={}".format(app_key)
    return hashlib.sha256(string_sign_temp.encode("utf-8")).hexdigest().upper()


def api_auth_validate(params, app_key, result):
    return create_params_sign(params, app_key) == result


def generate_auth_token(user_id):
    """
    根据用户 ID 生成 token
    :param user_id:
    :return:
    """
    token_byte = jwt.encode({'user_id': user_id, "timestamp": int(time())},
                            settings.SECRET_KEY,
                            algorithm='HS256')
    token_str = token_byte.decode('utf-8')
    return token_str


def extract_token_info(token):
    """
    抽取 token 中包含的信息
    :param token:
    :return:
    """
    token_info = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
    return token_info
